package grm.database;

import grm.info.IGood;
import grm.info.MerchantInfo;
import grm.role.Customer;
import grm.role.Merchant;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Scanner;

public class TextDatabase extends IDatabase{
    private ArrayList<Merchant> merchants;
    private ArrayList<Customer> customers;


    static TextDatabase instance;
    static {
        instance = new TextDatabase();
    }

    public static IDatabase getInstance() {
        return instance;
    }
    @Override
    public void initDatabase(String config) {
        setDataFile(config);
    }

    @Override
    public void listMerchantsAndGoods() {
        listMerchants();
    }

    @Override
    public boolean selectMerchantAndGood() {
        return false;
    }

    public void listMerchants() {
        for(Merchant m : merchants) {
            System.out.println(m);
        }
    }
    public void setDataFile(String path) {
        merchants = new ArrayList<Merchant>();
        Merchant merchant = new Merchant();
        System.out.println("Set data file");
        try(FileInputStream stream = new FileInputStream(path) ) {
            Scanner in = new Scanner(stream);
            String className = null;
            if(in.hasNextLine()) {
                className = in.nextLine();
            }
            Class cls = Class.forName(className);
//            System.out.println(cls.getConstructors()[1]);
            Constructor cons = cls.getConstructors()[1];
            while(in.hasNextLine()) {
                String line = in.nextLine();
                if(line=="---") continue;
                ArrayList<String> info = new ArrayList<>();

                for(;in.hasNextLine() && line!="---"; line=in.nextLine()) {
                    info.add(line);
                }
                merchant.add((IGood) cons.newInstance(info));
            }
            merchants.add(merchant);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

//        listMerchants();
    }
}
